package com.ewanghuiju.app.ui.my.activity;

import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ewanghuiju.app.R;
import com.ewanghuiju.app.app.App;
import com.ewanghuiju.app.app.Constants;
import com.ewanghuiju.app.base.BaseActivity;
import com.ewanghuiju.app.base.contract.my.MyTeamContract;
import com.ewanghuiju.app.model.bean.local.FansInfoBean;
import com.ewanghuiju.app.model.bean.response.TeamInfoResponBean;
import com.ewanghuiju.app.model.bean.response.UserInfoResponBean;
import com.ewanghuiju.app.model.dp.RealmHelper;
import com.ewanghuiju.app.presenter.my.MyTeamPresenter;
import com.ewanghuiju.app.ui.my.adapter.MyTeamListAdapter;
import com.ewanghuiju.app.util.AutoSoftUtils;
import com.ewanghuiju.app.util.ClipboardUtils;
import com.ewanghuiju.app.util.LoadingDialogUtils;
import com.ewanghuiju.app.util.StartActivityUtil;
import com.ewanghuiju.app.util.StringUtil;
import com.ewanghuiju.app.util.TimeUtils;
import com.ewanghuiju.app.util.nodoubleclick.AntiShake;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author sj  qq:751943509
 * @class 我的团队页面
 * @time 2020/2/24
 */
public class MyTeamActivity extends BaseActivity<MyTeamPresenter> implements MyTeamContract.View {
    //    @BindView(R.id.commonTabLayout)
//    CommonTabLayout commonTabLayout;
    @BindView(R.id.view_top)
    View viewTop;
    //    @BindView(R.id.viewpage)
//    ViewPager viewpage;
    @BindView(R.id.riv_my_head)
    RoundedImageView rivMyHead;
    @BindView(R.id.layout_main)
    RelativeLayout layoutMain;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_fans_all)
    TextView tvFansAll;
    @BindView(R.id.tv_fans_yys)
    TextView tvFansYys;
    @BindView(R.id.tv_fans_zs)
    TextView tvFansZs;
    @BindView(R.id.tv_today)
    TextView tvToday;
    @BindView(R.id.tv_zuoday)
    TextView tvZuoday;
    @BindView(R.id.tv_ejfans)
    TextView tvEjfans;
    @BindView(R.id.tv_fans_all_lab)
    TextView tvFansAllLab;
    @BindView(R.id.tv_fans_yys_lab)
    TextView tvFansYysLab;
    @BindView(R.id.tv_fans_zs_lab)
    TextView tvFansZsLab;
    @BindView(R.id.tv_today_lab)
    TextView tvTodayLab;
    @BindView(R.id.tv_zuoday_lab)
    TextView tvZuodayLab;
    @BindView(R.id.tv_ejfans_lab)
    TextView tvEjfansLab;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_yq_code)
    TextView tvYqCode;
    @BindView(R.id.tv_regist_time)
    TextView tvRegistTime;
    @BindView(R.id.tv_phone_copy)
    TextView tvPhoneCopy;
    @BindView(R.id.tv_wx_copy)
    TextView tvWxCopy;
    @BindView(R.id.relativeLayout_top)
    RelativeLayout relativeLayoutTop;
    @BindView(R.id.linearlayout_top)
    LinearLayout linearlayoutTop;
    @BindView(R.id.tv_type)
    TextView tvType;

    private int currentPage = 1;
    private int currentType = 1;
    private String searchText = "";

    private MyTeamListAdapter adapter;
    private UserInfoResponBean mUserInfoResponBean;

    @Override
    protected int getLayout() {
        return R.layout.activity_my_team;
    }

    @Override
    protected void initEventAndData() {
//        super.initEventAndData();
        mToolbar.setBackground(null);
        mToolbar.setNavigationIcon(R.mipmap.icon_fan_white);
        tvTitle.setTextColor(ContextCompat.getColor(mContext, R.color.white));

        GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT,
                new int[]{Color.parseColor("#24242E"), Color.parseColor("#2E2E3A")});
        viewTop.setBackground(gd);

        GradientDrawable gbbg = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT,
                new int[]{Color.parseColor("#24242E"), Color.parseColor("#2E2E3A")});
        layoutMain.setBackground(gbbg);

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            /** * @param v * @param actionId 针对软键盘,若是实体键盘actionId=0 * @param event 针对实体键盘,若是软键盘event=null * @return 返回true表示自己处理Enter事件,当imeOptions="actionSearch"时返回false此方法会被调用两次 */
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || event.getKeyCode() == KeyEvent.ACTION_DOWN) {
                    String words = etSearch.getText().toString().trim();
//                    if (TextUtils.isEmpty(words)) {
//                        StyleableToast.makeText(mContext, "请输入搜索手机号", Toast.LENGTH_SHORT, R.style.mytoast).show();
//                        return true;
//                    }
                    searchText = TextUtils.isEmpty(words) ? "" : words;
                    AutoSoftUtils.hideInput(etSearch);
                    LoadingDialogUtils.show(mContext);
                    currentPage = 1;
                    refreshLayout.resetNoMoreData();
                    mPresenter.getData(currentPage, searchText, currentType);
                    return true;
                }
                return false;
            }
        });

        initRecyleview();
    }


    private void initRecyleview() {
        recyclerview.setNestedScrollingEnabled(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        linearLayoutManager.setSmoothScrollbarEnabled(true);
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setLayoutManager(linearLayoutManager);
        adapter = new MyTeamListAdapter(R.layout.item_my_team_list);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                FansInfoBean fansInfoBean = (FansInfoBean) adapter.getItem(position);
                new StartActivityUtil(mContext, FansInfoActivity.class).putExtra(Constants.TEAM_FANS_ID,
                        fansInfoBean.getId())
                        .startActivity(true);
            }
        });
        adapter.setHasStableIds(true);
        recyclerview.setAdapter(adapter);
    }

    @Override
    protected void intSmartRefreshLayout() {

        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                LoadingDialogUtils.show(mContext);
                searchText = etSearch.getText().toString();
                currentPage++;
                mPresenter.getData(currentPage, searchText, currentType);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                LoadingDialogUtils.show(mContext);
                searchText = etSearch.getText().toString();
                currentPage = 1;
                refreshLayout.resetNoMoreData();
                mPresenter.getData(currentPage, searchText, currentType);
            }
        });
        resetTab();
        tvFansAllLab.setTextColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
        currentType = 1;
        onSelectedButton();
    }

    @OnClick({R.id.tv_yq_code, R.id.tv_phone_copy, R.id.tv_wx_copy,
            R.id.layout_today, R.id.layout_zuoday, R.id.layout_ejfans,
            R.id.layout_fans_all, R.id.layout_fans_yys, R.id.layout_fans_zs})
    public void doClick(View view) {
        if (AntiShake.check(view.getId())) {    //判断是否多次点击
            return;
        }
        switch (view.getId()) {
            case R.id.tv_yq_code:
                //复制邀请码
                if (mUserInfoResponBean != null) {
                    ClipboardUtils.copyText(mUserInfoResponBean.getNumber(), "复制成功");
                }
                break;
            case R.id.tv_phone_copy:
                //复制手机号
                if (mUserInfoResponBean != null && !TextUtils.isEmpty(mUserInfoResponBean.getMobile())) {
                    ClipboardUtils.copyText(mUserInfoResponBean.getMobile(), "复制成功");
                }
                break;
            case R.id.tv_wx_copy:
                //复制微信号
                if (mUserInfoResponBean != null && !TextUtils.isEmpty(mUserInfoResponBean.getWx_card())) {
                    ClipboardUtils.copyText(mUserInfoResponBean.getWx_card(), "复制成功");
                }
                break;
            case R.id.layout_today:
                //今日新增
                resetTab();
                tvTodayLab.setTextColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
                currentType = 4;
                onSelectedButton();
                break;
            case R.id.layout_zuoday:
                //昨日新增
                resetTab();
                tvZuodayLab.setTextColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
                currentType = 5;
                onSelectedButton();
                break;
            case R.id.layout_ejfans:
                //二级粉丝
                resetTab();
                tvEjfansLab.setTextColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
                currentType = 6;
                onSelectedButton();
                break;
            case R.id.layout_fans_all:
                //所有粉丝
                resetTab();
                tvFansAllLab.setTextColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
                currentType = 1;
                onSelectedButton();
                break;
            case R.id.layout_fans_yys:
                //下级运营商
                resetTab();
                tvFansYysLab.setTextColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
                currentType = 2;
                onSelectedButton();
                break;
            case R.id.layout_fans_zs:
                //直属粉丝
                resetTab();
                tvFansZsLab.setTextColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
                currentType = 3;
                onSelectedButton();
                break;
            default:
                break;
        }
    }

    /**
     * 点击不按钮   	1 全部粉丝 2 下级运营商 3 直属粉丝 4 今日粉丝 5 昨日新增 6 二级粉丝
     */
    public void onSelectedButton() {
        LoadingDialogUtils.show(mContext);
        searchText = etSearch.getText().toString();
        currentPage = 1;
        refreshLayout.resetNoMoreData();
        mPresenter.getData(currentPage, searchText, currentType);

    }

    /**
     * 重置tab
     */
    public void resetTab() {
        tvFansAllLab.setTextColor(ContextCompat.getColor(mContext, R.color.color_999));
        tvFansYysLab.setTextColor(ContextCompat.getColor(mContext, R.color.color_999));
        tvFansZsLab.setTextColor(ContextCompat.getColor(mContext, R.color.color_999));

        tvTodayLab.setTextColor(ContextCompat.getColor(mContext, R.color.color_666));
        tvZuodayLab.setTextColor(ContextCompat.getColor(mContext, R.color.color_666));
        tvEjfansLab.setTextColor(ContextCompat.getColor(mContext, R.color.color_666));
    }

    @Override
    protected int getTitleIntText() {
        return R.string.my_team_title;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .titleBar(mToolbar, true)
                .init();
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void showContent(TeamInfoResponBean bean) {
        //获取信息成功
        LoadingDialogUtils.dismissDialog_ios();
        if (bean == null) {
            return;
        }
        tvFansAll.setText(TextUtils.isEmpty(bean.getAll_fans()) ? "" : bean.getAll_fans());
        tvFansYys.setText(TextUtils.isEmpty(bean.getAll_operator()) ? "" : bean.getAll_operator());
        tvFansZs.setText(TextUtils.isEmpty(bean.getDirectly_fans()) ? "" : bean.getDirectly_fans());
        tvToday.setText(TextUtils.isEmpty(bean.getJin()) ? "" : bean.getJin());
        tvZuoday.setText(TextUtils.isEmpty(bean.getZuo()) ? "" : bean.getZuo());
        tvEjfans.setText(TextUtils.isEmpty(bean.getEr()) ? "" : bean.getEr());

        UserInfoResponBean userInfoResponBean = bean.getUserinfo();
        this.mUserInfoResponBean = userInfoResponBean;
        if (userInfoResponBean != null && !TextUtils.isEmpty(userInfoResponBean.getNumber())) {
//            relativeLayoutTop.setVisibility(View.VISIBLE);
//            linearlayoutTop.setVisibility(View.VISIBLE);
            tvType.setText("上级");
            Glide.with(mContext).load(userInfoResponBean.getHeadimg()).placeholder(R.mipmap.icon_default_head).error(R.mipmap.icon_default_head).into(rivMyHead);
            tvNickname.setText(StringUtil.getLengthTextByStr(userInfoResponBean.getNickname(), 6));
            tvYqCode.setText(TextUtils.isEmpty(userInfoResponBean.getNumber()) ? "" : userInfoResponBean.getNumber());

            String createTime = userInfoResponBean.getCreate_time();
            if (TextUtils.isEmpty(createTime)) {
                createTime = "";
            } else {
                createTime = "注册时间：" + TimeUtils.millis2String(TimeUtils.string2Millis(createTime), "yyyy.MM.dd");
            }
            tvRegistTime.setText(createTime);

            String phoneNum = "";
            if (userInfoResponBean.getIs_mobile() == 1) {
                phoneNum = TextUtils.isEmpty(userInfoResponBean.getMobile()) ? "" : userInfoResponBean.getMobile();
            } else {
                phoneNum = StringUtil.getFormatePhone(userInfoResponBean.getMobile());
            }
            tvPhoneCopy.setText(phoneNum);

            tvWxCopy.setText(TextUtils.isEmpty(userInfoResponBean.getWx_card()) ? "未设置" : userInfoResponBean.getWx_card());
        } else {
            tvType.setText("本人");
//            relativeLayoutTop.setVisibility(View.GONE);
//            linearlayoutTop.setVisibility(View.GONE);

            RealmHelper realmHelper = App.getAppComponent().realmHelper();
            UserInfoResponBean myUserInfoResponBean = realmHelper.getUserInfoResponBean();

            this.mUserInfoResponBean = myUserInfoResponBean;

            Glide.with(mContext).load(myUserInfoResponBean.getHeadimg()).placeholder(R.mipmap.icon_default_head).error(R.mipmap.icon_default_head).into(rivMyHead);
            tvNickname.setText(StringUtil.getLengthTextByStr(myUserInfoResponBean.getNickname(), 6));
            tvYqCode.setText(StringUtil.getLengthTextByStr(myUserInfoResponBean.getNumber(), 8));

            String myCreateTime = myUserInfoResponBean.getCreate_time();
            if (TextUtils.isEmpty(myCreateTime)) {
                myCreateTime = "";
            } else {
                myCreateTime = "注册时间：" + TimeUtils.millis2String(TimeUtils.string2Millis(myCreateTime), "yyyy.MM.dd");
            }
            tvRegistTime.setText(myCreateTime);

            String phoneNum = "";
            if (myUserInfoResponBean.getIs_mobile() == 1) {
                phoneNum = TextUtils.isEmpty(myUserInfoResponBean.getMobile()) ? "" : myUserInfoResponBean.getMobile();
            } else {
                phoneNum = StringUtil.getFormatePhone(myUserInfoResponBean.getMobile());
            }
            tvPhoneCopy.setText(phoneNum);

            tvWxCopy.setText(TextUtils.isEmpty(myUserInfoResponBean.getWx_card()) ? "未设置" : myUserInfoResponBean.getWx_card());
        }

        List<FansInfoBean> list = bean.getList();
        if (list == null) {
            list = new ArrayList<>();
        }
        if (currentPage == 1) {
            if (list.size() < Constants.NUM_OF_PAGE_TWO) {
                refreshLayout.finishRefreshWithNoMoreData();
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishRefresh();
            }
            adapter.setNewData(list);
        } else {
            if (list.size() < Constants.NUM_OF_PAGE_TWO) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore();
            }
            adapter.addData(list);
        }
    }

    @Override
    public void showContentError() {
        if (currentPage == 1) {
            refreshLayout.finishRefresh();
        } else {
            currentPage--;
            refreshLayout.finishLoadMore();
        }
    }
}
